<?php
/**
 * 后台管理员登录模型
 * Created by PhpStorm.
 * User: yui
 * Date: 2017/4/16
 * Time: 15:36
 */

namespace common\models;

use Yii;
use yii\base\Model;

class UserLogin extends Model
{
    public $username;
    public $password;
    public $remember = true;
    private $_user;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required'],

            ['username', 'trim'],
            ['username', 'string', 'min' => 5],

            ['password', 'trim'],
            ['password', 'string', 'min' => 6],
            ['password', 'validatePassword'],

            ['remember', 'boolean'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'username' => '账户',
            'password' => '密码',
        ];
    }

    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (empty($user) || !$user->validatePassword($this->password)) {
                $this->addError($attribute, '账号或密码错误');
            }
        }
    }

    public function login()
    {
        $User = $this->getUser();
        $rs = Yii::$app->user->login($User, 14400);
        if ($rs) {
            //如果token存在,获取缓存对象
            $cache = Yii::$app->cache;
            if ($User->token) {
                $cacheUserObj = $cache->get($User->token);
            }
            //如果token不存在，或者token过期
            if (empty($User->token) || empty($cacheUserObj)) {
                //新建token
                $User->generateToken();
                //更新到数据库
                $User->update();
            }
            //缓存用户对象
            $cache->set($User->token, $User, OC['session_lifetime']);
        }
        return $rs;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }


}